package hu.issue.web;

import hu.issue.ejb.ProjectService;
import hu.issue.ejb.TaskService;
import hu.issue.entity.Project;
import hu.issue.entity.Task;
import hu.issue.entity.User;
import hu.issue.exceptions.ProjectNotFoundException;
import hu.issue.framework.web.Constants;
import hu.issue.framework.web.controller.AbstractFormController;
import hu.issue.framework.web.controller.Inject;
import hu.issue.framework.web.controller.RequiredRole;
import hu.issue.framework.web.servlet.SessionUtil;
import hu.issue.framework.web.validation.DateValidator;
import hu.issue.framework.web.validation.ErrorMessages;
import hu.issue.framework.web.validation.RequestValidation;
import hu.issue.framework.web.validation.RequiredValidator;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequiredRole(Constants.ROLE_USER)
public class NewTaskController extends AbstractFormController {
	@Inject
	private TaskService taskService;
	@Inject
	private ProjectService projectService;

	@Override
	protected void buildModel(final HttpServletRequest request) {
		final int projectId = Integer.parseInt(request.getParameter("projectId"));
		try {
			final Project project = this.projectService.findProjectById(projectId);

			request.setAttribute("project", project);

		} catch (final ProjectNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected String handleSubmission(final HttpServletRequest request, final HttpServletResponse response, final ErrorMessages messages) throws Exception {
		final String name = request.getParameter("name");
		final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		final Date dueDate = format.parse(request.getParameter("dueDate"));
		final User user = SessionUtil.getUser(request.getSession());
		this.taskService.createTask(new Task(name, dueDate, user));
		return "redirect:project.do?projectId=" + request.getParameter("projectId");
	}

	@Override
	protected void buildValidation(final RequestValidation validation) {
		validation.addValidator(new RequiredValidator("name", "Feladat neve kötelező"));
		validation.addValidator(new RequiredValidator("dueDate", "Határidő kötelező"));
		validation.addValidator(new DateValidator("dueDate", "Határidő formátuma: év-hónap-nap", "yyyy-MM-dd"));
	}
}
